import React, { useContext, useMemo, useState } from 'react';
import { useRequest } from 'ahooks';
import moment from 'moment';
import { Typography, Drawer, Row, Select } from 'antd';
import Tabs from '@/components/MarketingMap/Tabs';
import { LeftOutlined } from '@ant-design/icons';
import DateFrom from '@/components/MarketingMap/DateFrom';
import LineChart from '@/components/MarketingMap/LineChart';
import CircularChart from '@/components/MarketingMap/CircularChart';
import { fetchTraffic, fetchComparison } from '@/services/marketingMap/overallAnalysis';
import { formatDate } from '@/utils/marketingMap/utils';
import OverallContext from '../context';
import EmptyState from '@/components/MarketingMap/EmptyState';
import styles from '../styles/panel.less';

const toData = (data: { count: number; name: number; series: string }[], is = false) => {
  if (!is) {
    return data.map(item => ({
      value: item?.count || 0,
      name: item.name,
    }));
    // return data?.map(item => ({ value: item.count, name: mapper[item.type] }));
  } else {
    return data?.map(item => ({ value: item.count, name: item.name }));
  }
};
const LineCard: React.FC<{
  code: string;
  name: string;
  isAuth: boolean;
}> = ({ name, code, isAuth }) => {
  const { query, date } = useContext(OverallContext);
  const [select, setSelect] = useState('vehicleCount');
  const [trend, setTrend] = useState(0);
  const { data, loading } = useRequest(() => fetchTraffic({ ...query, trend, toStore: code }), {
    refreshDeps: [query, code, trend],
  });

  const [xAxis, store, toStore] = useMemo(() => {
    if (!Object.keys(data || {}).length) return [];

    const xAxis = data.storeData?.map((item: any) => item.date) || [];
    const store = data.storeData?.map((item: any) => item[select]) || [];
    const toStore = data.toStoreData?.map((item: any) => item[select]) || [];

    return [xAxis, store, toStore];
  }, [data, select]);

  return (
    <div>
      <Typography className={styles.title} style={{ paddingBottom: 4 }}>
        <Typography.Text strong>售后流量对比</Typography.Text>
      </Typography>
      <Row align="middle" justify="space-between">
        <span>
          统计时间：
          {moment(date.summaryDate).subtract(date.timeRange, 'month')?.format('YYYY-MM-DD')} ~{' '}
          {date.summaryDate}
        </span>
        <Select value={select} onChange={setSelect} style={{ width: 126 }}>
          <Select.Option value="vehicleCount">售后车辆数</Select.Option>
          <Select.Option value="aftersalesCount">保客售后次数</Select.Option>
          {isAuth && <Select.Option value="income">售后收入(元)</Select.Option>}
        </Select>
      </Row>
      <Tabs value={trend} onChange={setTrend} tabs={['日趋势', '周趋势', '月趋势']} />
      <EmptyState empty={!toStore?.length} loading={loading}>
        <LineChart
          xAxis={xAxis?.map((item: string) =>
            trend === 2 ? formatDate(item, 'year') : formatDate(item),
          )}
          bottom={50}
          // width={540}
          series={[
            {
              name: '我的专营店',
              data: store,
              type: 'line',
              smooth: true,
            },
            {
              name,
              data: toStore,
              type: 'line',
              smooth: true,
            },
          ]}
        />
      </EmptyState>
    </div>
  );
};

const FriendsComparison: React.FC<{
  toStore: { code: string; name: string };
  visible: boolean;
  onClose: () => void;
  isAuth: boolean;
}> = ({ visible, toStore, onClose, isAuth }) => {
  const { code, name } = toStore;
  const { query, date, onSubmit } = useContext(OverallContext);

  const { loading, run, data } = useRequest(() => fetchComparison({ ...query, toStore: code }), {
    refreshDeps: [query, code],
    refreshDepsAction: () => {
      if (visible) {
        run();
      }
    },
  });

  const projectData = useMemo(() => {
    if (!data?.[0]) return null;
    const { storeData, toStoreData } = data[0];

    return [
      { name: '我的售后店', data: toData(storeData) },
      { name: name, data: toData(toStoreData) },
    ];
  }, [data?.[0]]);

  const seriesData = useMemo(() => {
    if (!data?.[1]) return null;
    const { storeData, toStoreData } = data[1];

    return [
      { name: '我的售后店', data: toData(storeData, true) },
      { name: name, data: toData(toStoreData, true) },
    ];
  }, [data?.[1]]);

  return (
    <Drawer
      title="与友商对比"
      placement="right"
      onClose={onClose}
      open={visible}
      width="100%"
      getContainer={false}
      style={{ position: 'absolute', top: -52 }}
      mask={false}
      closeIcon={<LeftOutlined />}
      bodyStyle={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 12 }}
    >
      <DateFrom value={date} onChange={onSubmit} />
      <LineCard isAuth={isAuth} code={code} name={name} />
      <EmptyState empty={!projectData?.length} loading={loading}>
        <div>
          <Typography className={styles.title}>
            <Typography.Text strong>售后项目对比</Typography.Text>
          </Typography>
          <CircularChart toStore={name} data={projectData} />
        </div>
      </EmptyState>
      <EmptyState empty={!seriesData?.length} loading={loading}>
        <div>
          <Typography className={styles.title}>
            <Typography.Text strong>售后车系对比</Typography.Text>
          </Typography>
          <CircularChart toStore={name} data={seriesData} />
        </div>
      </EmptyState>
    </Drawer>
  );
};

export default FriendsComparison;
